#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"global.h"
filewriteauto(CI *p){
	FILE *fp1;
	CI *p1;
	if((fp1=fopen("autoaddress.dat","w"))==NULL){
		printf("\ncannot open the file!\n");
		exit(0);
	}
/*	if((fp2=fopen("forever.dat","a"))==NULL){
		printf("\ncannot open the file!\n");
		exit(0);
	}				*/
	for(p1=p;p1!=NULL;p1=p1->next){
	/*	while(fgetc(fp2)!=EOF){
			i++;
			p2=(CI *)malloc(sizeof(CI));
			fscanf(fp2,"%s %s %c %d %s ",p2->name,p2->telphone,&p2->sex,&p2->age,p2->phone);
			if((strcmp(p2->name,p1->name)==0)&&(strcmp(p2->phone,p1->phone)==0)&&(strcmp(p2->telphone,p1->telphone)==0)&&p1->age==p2->age&&p1->sex==p2->sex)
				j++;
			free(p2);
		}
		if(i==j)
			fprintf(fp2,"%s %s %c %d %s ",p1->name,p1->telphone,p1->sex,p1->age,p1->phone);			*/
		fprintf(fp1,"%s %s %c %d %s\n",p1->name,p1->telphone,p1->sex,p1->age,p1->phone);
	//	printf("pp\n");
	}
	fclose(fp1);
//	fclose(fp2);
}
filewritefor(CI *p){
	FILE *fp2;
	int i=0,j=0;
	CI *p1;
	CI p2;
	if((fp2=fopen("forever.dat","a+"))==NULL){
		printf("\ncannot open the file!\n");
		exit(0);
	}	
//	printf("pp\n");
	for(p1=p,i=0,j=0;p1!=NULL;p1=p1->next){
		rewind(fp2);
		while(fgetc(fp2)!=EOF){
		//	printf("pp\n");
		//	p2=(CI *)malloc(sizeof(CI));
			fseek(fp2,-1,SEEK_CUR);
			fscanf(fp2,"%s %s %c %d %s",p2.name,p2.telphone,&p2.sex,&p2.age,p2.phone);
			fgetc(fp2);
//			printf("ppp\n");
			if(!(strcmp(p2.name,p1->name))&&!(strcmp(p2.phone,p1->phone))&&!(strcmp(p2.telphone,p1->telphone))&&p1->age==p2.age&&p1->sex==p2.sex)
				j++;
		//	free(p2);
//			printf("pp\n");
		}
		if(0==j)
			fprintf(fp2,"%s %s %c %d %s\n",p1->name,p1->telphone,p1->sex,p1->age,p1->phone);	
	}
	fclose(fp2);
}
CI * fileread(char key){
	FILE *fp;
	CI *p,*phead;
	phead=NULL;
	p=NULL;
	if(key=='R'){
		if((fp=fopen("forever.dat","r"))==NULL){
			printf("\ncannot open the file!\n");
			return(NULL);
			exit(0);
		}
	}
	else
		if((fp=fopen("autoaddress.dat","r"))==NULL){
			printf("\ncannot open the file!\n");
			return(NULL);
			exit(0);
		}
	while(fgetc(fp)!=EOF){
			fseek(fp,-1,SEEK_CUR);
			p=(CI *)malloc(sizeof(CI));
//			printf("pp\n");
			fscanf(fp,"%s %s %c %d %s",p->name,p->telphone,&p->sex,&p->age,p->phone);
			p->next=phead;
			phead=p;
		
	}
	fclose(fp);
	phead=phead->next;
	return(phead);
}



